package com.personal.portal.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.personal.portal.common.entity.Result;
import com.personal.portal.admin.entity.Skill;
import com.personal.portal.admin.entity.SkillCategory;
import com.personal.portal.admin.mapper.SkillCategoryMapper;
import com.personal.portal.admin.mapper.SkillMapper;
import com.personal.portal.admin.service.SkillCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 技能分类服务实现类
 *
 * @author zhanghui
 * @version 1.0.0
 * @since 2025-11-10
 */
@Service
public class SkillCategoryServiceImpl implements SkillCategoryService {

    @Resource
    private SkillCategoryMapper skillCategoryMapper;

    @Resource
    private SkillMapper skillMapper;

    @Override
    public SkillCategory queryById(Long id) {
        validateId(id);
        return skillCategoryMapper.selectOneById(id);
    }

    @Override
    public SkillCategory queryByEntity(SkillCategory skillCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(skillCategory);
        return skillCategoryMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<SkillCategory> queryList(SkillCategory skillCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(skillCategory);
        List<SkillCategory> categories = skillCategoryMapper.selectListByQuery(queryWrapper);

        // 计算每个分类的技能数量
        calculateSkillCount(categories);
        return categories;
    }

    @Override
    public Result.PageResult<SkillCategory> queryPage(int pageNum, int pageSize, SkillCategory skillCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(skillCategory);
        Page<SkillCategory> paginate = skillCategoryMapper.paginate(pageNum, pageSize, queryWrapper);

        // 计算每个分类的技能数量
        calculateSkillCount(paginate.getRecords());
        return new Result.PageResult<>(paginate.getRecords(), paginate.getTotalRow(), pageNum, pageSize);
    }

    @Override
    public int insert(SkillCategory skillCategory) {
        validateSkillCategory(skillCategory);
        return skillCategoryMapper.insert(skillCategory);
    }

    @Override
    public int update(SkillCategory skillCategory) {
        if (skillCategory.getId() == null) {
            throw new IllegalArgumentException("技能分类ID不能为空");
        }
        validateId(skillCategory.getId());
//        validateSkillCategory(skillCategory);

        SkillCategory existing = skillCategoryMapper.selectOneById(skillCategory.getId());
        if (existing == null) {
            throw new IllegalArgumentException("技能分类信息不存在");
        }

        return skillCategoryMapper.update(skillCategory);
    }

    @Override
    public int deleteById(Long id) {
        validateId(id);

        SkillCategory existing = skillCategoryMapper.selectOneById(id);
        if (existing == null) {
            throw new IllegalArgumentException("技能分类信息不存在");
        }

        return skillCategoryMapper.deleteById(id);
    }

    @Override
    public List<Long> deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<Long> successIds = new ArrayList<>();
        List<Long> failedIds = new ArrayList<>();

        for (Long id : ids) {
            try {
                validateId(id);

                SkillCategory existing = skillCategoryMapper.selectOneById(id);
                if (existing == null) {
                    failedIds.add(id);
                    continue;
                }

                int result = skillCategoryMapper.deleteById(id);
                if (result > 0) {
                    successIds.add(id);
                } else {
                    failedIds.add(id);
                }
            } catch (Exception e) {
                failedIds.add(id);
            }
        }

        if (!successIds.isEmpty()) {
            return successIds;
        } else {
            throw new IllegalArgumentException("批量删除失败");
        }
    }

    /**
     * 验证技能分类信息
     */
    private void validateSkillCategory(SkillCategory skillCategory) {
        if (skillCategory == null) {
            throw new IllegalArgumentException("技能分类信息不能为空");
        }
        if (StringUtils.isBlank(skillCategory.getName())) {
            throw new IllegalArgumentException("分类名称不能为空");
        }
    }

    /**
     * 验证ID
     */
    private void validateId(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的技能分类ID");
        }
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper buildQueryWrapper(SkillCategory skillCategory) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SkillCategory::getId, skillCategory.getId(), skillCategory.getId() != null);
        queryWrapper.like(SkillCategory::getName, skillCategory.getName(), StringUtils.isNotEmpty(skillCategory.getName()));
        queryWrapper.like(SkillCategory::getDescription, skillCategory.getDescription(), StringUtils.isNotEmpty(skillCategory.getDescription()));
        queryWrapper.eq(SkillCategory::getStatus, skillCategory.getStatus(), skillCategory.getStatus() != null);

        queryWrapper.orderBy(SkillCategory::getSortOrder, true);
        queryWrapper.orderBy(SkillCategory::getName, true);
        queryWrapper.orderBy(SkillCategory::getId, true);
        return queryWrapper;
    }

    /**
     * 计算每个分类的技能数量
     */
    private void calculateSkillCount(List<SkillCategory> categories) {
        if (categories == null || categories.isEmpty()) {
            return;
        }

        for (SkillCategory category : categories) {
            QueryWrapper skillQueryWrapper = new QueryWrapper();
            skillQueryWrapper.eq(Skill::getCategoryId, category.getId());

            List<Skill> skillList = skillMapper.selectListByQuery(skillQueryWrapper);
            category.setSkillCount((long) skillList.size());
            if (!skillList.isEmpty()) {
                List<String> collect = skillList.stream().map(Skill::getName).collect(Collectors.toList());
                category.setSkillNameList(collect);
            }
        }
    }
}